﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml;
using System.Net;
using System.Text;
using BusinessLayer;
using DataLayer;
using InterIMAP;

public partial class Widgets_Mail_Email_grab : System.Web.UI.Page
{
   private static int CompareMessages(IMAPMessage x, IMAPMessage y)
   {
      return x.Date.CompareTo(y.Date);
   }

   protected void Page_Load(object sender, EventArgs e)
   {
      XElement result = new XElement("result");
      XElement Status = new XElement("Status");
      Status.Value = "Permission Denied";
      using (new EntLib.EntTimedLog(Profile.UserName, GetType().ToString(), Request.QueryString.ToString(), true))
      {
         int TabWidgetID = 0;
         try
         {
            TabWidgetID = Typecast.ToInt32(Request.QueryString["id"]);
         }
         catch
         {
            TabWidgetID = 0;
         }


         if (TabWidgetID > 0)
         {
            string Action = "";

            try
            {
               Action = Request.QueryString["action"].ToLower();
            }
            catch
            {
            }

            using (var db = DatabaseHelper.GetDashboardData())
            {
               var theTab = (from tw in db.TabWidgets
                             where tw.Id == TabWidgetID
                             select new { tw.Tab.ID, tw.State });
               if (theTab.Count() == 1)
               {
                  //make sure only 1 result is returned, after all, 1 widgetinstance is link to 1 tab
                  var F = new Facade(Functions.GetUserProviderKey(), Profile.UserName);

                  //now confirm user has read permission to this tab
                  var theResult = theTab.Single();

                  if (F.Tab_CheckReadPermission(theResult.ID))
                  {
                     if (theResult.State.Length > 0)
                     {
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(theResult.State);
                        var Node_State = doc["state"];
                        var UserID = "";
                        try
                        {
                           UserID = Node_State["UserID"].ChildNodes[0].Value;
                        }
                        catch
                        {
                        }
                        var Password = "";
                        try
                        {
                           Password = Node_State["Enc_Password"].ChildNodes[0].Value;
                        }
                        catch
                        {
                        }
                        
                        if (UserID.Length > 0 && Password.Length > 0)
                        {
                           var IMAP = Node_State["IMAP"].ChildNodes[0].Value;
                           var IMAP_Secure = Node_State["IMAP_Secure"].ChildNodes[0].Value;

                           IMAPConfig config = new IMAPConfig();
                           config.Host = IMAP;
                           config.UserName = UserID;
                           config.Password = Password;
                           config.UseSSL = IMAP_Secure == "1";
                           config.DefaultFolderName = "INBOX";
                           config.AutoLogon = true;
                           config.DebugMode = false;
                           config.AutoGetMsgID = false;
                           config.AutoSyncCache = false;
                           config.LogFile = "";
                           config.DebugDetail = IMAPConfig.DebugDetailLevel.ErrorsOnly;
                           config.CacheFile = "";

                           DateTime xStart = DateTime.Now;
                           IMAPClient client = null;
                           try
                           {
                              client = new IMAPClient(config, null, 5);
                           }
                           catch (IMAPException ex)
                           {
                              Status.Value = ex.Message;
                           }

                           if (client != null)
                           {
                              var Folder = client.Folders[config.DefaultFolderName];
                              if (Folder == null)
                              {
                                 Status.Value = "No such folder: " + config.DefaultFolderName;
                              }
                              else
                              {
                                 if (Action.Length < 1)
                                 {
                                    //get all messages
                                    if (Folder.Messages != null)
                                    {
                                       XElement Emails = new XElement("Emails");

                                       //Grab all the UIDs
                                       ArrayList UIDs = new ArrayList();
                                       foreach (var msg in Folder.Messages)
                                          UIDs.Add(msg.Uid);

                                       //Sort them out
                                       UIDs.Sort();

                                       int idx_End = UIDs.Count - 1;
                                       int idx_Start = Math.Max(-1, idx_End - 20);
                                       for (; idx_End > idx_Start; idx_End--)
                                       {
                                          var msg = Folder.GetMessageByID((int)UIDs[idx_End]);

                                          XElement Email = new XElement("Email" + msg.Uid);
                                          XElement xUID = new XElement("UID");
                                          XElement xDate = new XElement("Date");
                                          XElement xFrom = new XElement("From");
                                          XElement xEmailFrom = new XElement("EmailFrom");
                                          XElement xSubject = new XElement("Subject");
                                          XElement xBody = new XElement("Body");
                                          XElement xText = new XElement("Text");

                                          xUID.Value = msg.Uid.ToString();
                                          xDate.Value = msg.Date.ToString("dd MMM yyyy<br />hh:mm tt");

                                          if (msg.From[0].DisplayName.Length > 0)
                                             xFrom.Value = msg.From[0].DisplayName;
                                          else
                                             xFrom.Value = msg.From[0].Address;

                                          if (xFrom.Value.Length > 25)
                                             xFrom.Value = xFrom.Value.ToString().Substring(0, 22) + "...";

                                          xEmailFrom.Value = msg.From[0].Address;
                                          xSubject.Value = msg.Subject;
                                          if (xSubject.Value.Length > 50)
                                             xSubject.Value = xSubject.Value.Substring(0, 47) + "...";

                                          if (msg.TextData != null && msg.TextData.TextData.Length > 0)
                                          {
                                             xBody.Value = msg.TextData.TextData;
                                          }
                                          else
                                          {
                                             //text/html;
                                             //text/plain;
                                             StringBuilder sb_Html = new StringBuilder();
                                             StringBuilder sb_Text = new StringBuilder();
                                             foreach (var Part in msg.BodyParts)
                                             {
                                                if (Part.ContentType.ToLower().IndexOf("text/plain") > -1)
                                                {
                                                   sb_Text.Append("<br>" + Part.TextData);
                                                }
                                                else if (Part.ContentType.ToLower().IndexOf("text/html") > -1)
                                                {
                                                   sb_Html.Append("<br>" + Part.TextData);
                                                }
                                             }
                                             if (sb_Html.Length > 0)
                                                xBody.Value = sb_Html.ToString();
                                             else
                                                xBody.Value = sb_Text.ToString();
                                          }
                                          xText.Value = Functions.StripHtml(xBody.Value.ToString());

                                          Email.Add(xUID);
                                          Email.Add(xDate);
                                          Email.Add(xEmailFrom);
                                          Email.Add(xFrom);
                                          Email.Add(xSubject);
                                          Email.Add(xBody);
                                          Email.Add(xText);
                                          Emails.Add(Email);
                                       }

                                       result.Add(Emails);
                                       TimeSpan TS = new TimeSpan(DateTime.Now.Ticks - xStart.Ticks);
                                       Status.Value = "OK";
                                       XElement Duration = new XElement("Duration");
                                       Duration.Value = TS.TotalSeconds.ToString();
                                       result.Add(Duration);
                                    }
                                    else
                                    {
                                       Status.Value = "No messages in folder";
                                    }
                                 }
                                 else if (Action[0] == 'm')
                                 {
                                    //get particular message
                                    int MessageID = Typecast.ToInt32(Action.Substring(1));
                                    var Msg = Folder.GetMessageByID(MessageID);
                                    if (Msg == null)
                                    {
                                       Status.Value = "Message does not exist on server: " + MessageID;
                                    }
                                    else
                                    {
                                       XElement UID = new XElement("UID");
                                       UID.Value = Msg.TextData.TextData;
                                       result.Add(UID);
                                       Status.Value = "OK";
                                    }
                                 }
                                 client.Logoff();
                              }
                           }
                        }
                        else
                        {
                           Status.Value = "Click <a href='javascript:void(0)' onclick='$WI(" + TabWidgetID + ").Edit();'>here</a> to configure your mail client";
                        }
                     }
                  }
               }
            }
         }
      }
      result.AddFirst(Status);
      Response.Write(result.ToString(SaveOptions.None));
   }
}
